package com.ysy.logistics.controller.supplier;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.annotation.SaMode;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ysy.common.myenum.StatusEnum;
import com.ysy.common.resp.ResultData;
import com.ysy.logistics.entities.supplier.SupGoods;
import com.ysy.logistics.entities.supplier.Supplier;
import com.ysy.logistics.entities.supplier.dto.SupGoodsDto;
import com.ysy.logistics.entities.supplier.vo.SupplierQueryVO;
import com.ysy.logistics.entities.system.SysUser;
import com.ysy.logistics.myannotation.OperateLog;
import com.ysy.logistics.service.supplier.SupGoodsService;
import com.ysy.logistics.util.PageInfo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.URLDecoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Objects;
import java.util.UUID;

/**
 * @ClassDescription:
 * @Author:姚斯羽
 * @Create:2025/3/26 0:19
 **/
@Slf4j
@RestController
@RequestMapping(value = "/supGoods",name = "供应商商品")
@Tag(name = "供应商商品管理",description = "supgoods表的CRUD")
@CrossOrigin
public class SupGoodsController {

    @Resource
    private SupGoodsService supGoodsService;

    @Value("${custom.file.save_path:/home/archives}")
    private String savePath;

    // 商品配图默认路径
    private static final String DEFAULT_PIC_PATH = File.separator  + "supGoods" + File.separator + "pic" + File.separator;

    @PostMapping( "/listByPage")
    @Operation(summary = "分页查询供应商",description = "分页查询供应商")
    @OperateLog("查询供应商商品")
    public ResultData<Page<SupGoodsDto>> listByPage(@RequestBody PageInfo<SupplierQueryVO> pageInfo){
        return ResultData.success(supGoodsService.listByPage(pageInfo));
    }
    @PostMapping( "/listSupGoodsPage")
    @Operation(summary = "分页查询商品",description = "查询供应商商品")
    @OperateLog("查询商品")
    public ResultData<Page<SupGoods>> listSupGoodsPage(@RequestBody PageInfo<SupGoods> pageInfo){
        return ResultData.success(supGoodsService.listSupGoodsPage(pageInfo));
    }

    @PostMapping("/saveFile")
    @Operation(summary = "供应商商品添加",description = "携带文件信息")
    @OperateLog("供应商商品添加")
    public ResultData saveFile(@RequestParam("file") MultipartFile file, SupGoods supGoods){
        if (file.isEmpty()) {
            return ResultData.fail("上传文件不能为空");
        }
        //文件类型
        String contentType = file.getContentType();
        if (!contentType.equals("image/jpeg") && !contentType.equals("image/png")) {
            return ResultData.fail("上传文件格式不正确");
        }
        //生成文件名
        String fileName = UUID.randomUUID() + "." + file.getOriginalFilename().split("\\.")[1];
        //保存文件
        try {
            Path dir = Paths.get(savePath+ DEFAULT_PIC_PATH);
            Files.createDirectories(dir);
            file.transferTo(dir.resolve(fileName));
            //保存商品信息
            supGoods.setPic(DEFAULT_PIC_PATH + fileName);
            if (StringUtils.isNotBlank(supGoods.getId())&& Objects.nonNull(supGoodsService.getById(supGoods.getId()))){
                supGoodsService.updateById(supGoods);
            }else {
                supGoodsService.save(supGoods);
            }

            return ResultData.success("");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @PostMapping("/save")
    @Operation(summary = "供应商商品添加",description = "携带文件信息")
    @OperateLog("供应商商品添加")
    public ResultData save(@RequestBody SupGoods supGoods){
        if (StringUtils.isNotBlank(supGoods.getId()) && Objects.nonNull(supGoodsService.getById(supGoods.getId()))){
            supGoodsService.updateById(supGoods);
        }else {
            supGoodsService.save(supGoods);
        }
            return ResultData.success("");

    }

    @GetMapping(value = "/changeStatus/{id}")
    @Operation(summary = "修改商品状态",description = "修改商品状态")
    @OperateLog("修改商品状态")
    public ResultData changeStatus(@PathVariable("id") String id) {
        SupGoods supGoods = supGoodsService.getById(id);
        if (Objects.isNull(supGoods)){
            return ResultData.fail("商品不存在");
        }
        SupGoods update = new SupGoods();
        update.setId(id);
        if (StringUtils.equals(supGoods.getStatus(), StatusEnum.ENABLE.getCode())){
            update.setStatus(StatusEnum.DISABLE.getCode());
        }else {
            update.setStatus(StatusEnum.ENABLE.getCode());
        }
        supGoodsService.updateById(update);
        return ResultData.success("修改供应商状态成功");
    }

    @GetMapping(value = "/delete/{id}")
    @Operation(summary = "删除商品",description = "删除商品")
    @OperateLog("删除商品")
    public ResultData delete(@PathVariable("id") String id) {
        SupGoods supGoods = supGoodsService.getById(id);
        if (Objects.isNull(supGoods)){
            return ResultData.fail("商品不存在");
        }
        if (supGoods.getStatus().equals("0")){
            return ResultData.fail("商品状态为启用，不能删除");
        }
        //删除供应商商品
        supGoodsService.removeById(id);
        return ResultData.success("删除商品成功");
    }


}
